package com.huitone.smspfm.dao.oracle;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.util.StringUtils;

import com.huitone.smspfm.dao.oracle.entity.SmsCallTest;


public class SmsCallTestDao extends BaseDao<SmsCallTest> {
	
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
	private static String sqlDateStr = "yyyy-mm-dd-hh24-mi-ss";
	
	@Override
	public List<SmsCallTest> getAllObj() {
		return jdbcTemplate.query("SELECT * FROM " + tableName + " WHERE SEND_RESULT IS NULL AND SM_SEQ IS NULL ", new BeanPropertyRowMapper<SmsCallTest>(SmsCallTest.class));
	}
	
	
	public List<SmsCallTest> getAllObj(Date date) {
		return jdbcTemplate.query("SELECT * FROM " + tableName + " WHERE SEND_RESULT IS NULL AND SM_SEQ IS NULL " +" AND LAST_MOD_TIME >= "
	+" TO_DATE( ' " + dateFormat.format(date) +" ',' "+sqlDateStr +" ') "
	, new BeanPropertyRowMapper<SmsCallTest>(SmsCallTest.class));
	}
	
	public int updateObjAllForSeq(List<SmsCallTest> list){
		int result = 0;
		Iterator<SmsCallTest> it = list.iterator();
		while(it.hasNext()){
			result += updateObjForSeq(it.next());
		}		
		return result;		
	}
	
	public int updateObjForSeq(SmsCallTest sms){
		boolean isSendPort = ! StringUtils.isEmpty(sms.getSendResult());
		String sql = "UPDATE " + tableName +" SET "
				+ " LAST_MOD_TIME = " + " TO_DATE( ' " + dateFormat.format(new Date()) +" ',' "+sqlDateStr +" ') " 
				+ (isSendPort ? " ,SEND_RESULT = '" +sms.getSendResult() +"'": "")
				+ "  WHERE SM_SEQ = '" + sms.getSmSeq()+"'";
		return jdbcTemplate.update(sql);	
	}
	
	
	public int updateObjAll(List<SmsCallTest> list){
		int result = 0;
		Iterator<SmsCallTest> it = list.iterator();
		while(it.hasNext()){
			result += updateObj(it.next());
		}		
		return result;		
	}

	public int updateObj(SmsCallTest sms){
		boolean isSendPort = ! StringUtils.isEmpty(sms.getSendResult());
		boolean isSeq = ! StringUtils.isEmpty(sms.getSmSeq());
		String sql = "UPDATE " + tableName +" SET "
				+ " LAST_MOD_TIME = " + " TO_DATE( ' " + dateFormat.format(new Date()) +" ',' "+sqlDateStr +" ') " 
				+ (isSendPort ? " ,SEND_RESULT = '" +sms.getSendResult() +"'": "")
				+ (isSeq ? " ,SM_SEQ = '" +sms.getSmSeq()+"'" : "")
				+ "  WHERE REC_ID = '" + sms.getRecId()+"'";
		return jdbcTemplate.update(sql);	
	}
}
